package com.yimi.appstore.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;

import com.yimi.appstore.R;
import com.yimi.appstore.YimiApplication;
import com.yimi.appstore.adapter.DownloadExpandAdapter;
import com.yimi.appstore.adapter.DownloadJobAdapter;
import com.yimi.appstore.adapter.MyViewPager;
import com.yimi.appstore.download2.DownloadEntity;
import com.yimi.appstore.download2.DownloadJob;
import com.yimi.appstore.download2.DownloadManager;
import com.yimi.appstore.view.SyncHorizontalScrollView;

public class DownloadManagementActivity extends Activity {

	Context context;
	private SyncHorizontalScrollView shsView;
	private RelativeLayout rl_scroll;
	private RadioGroup tab_content;
	private ImageView cursor;
	private ViewPager vPager;
	private List<RadioButton> rb_pages = new ArrayList<RadioButton>();
	private int mCurrentCheckedRadioLeft;// 当前的Tab距离左侧的距离
	private List<View> listViews;
	private LayoutInflater mInflater;
	private int cursorWidth;// 宽度
	private List<String> channels = new ArrayList<String>();
	private DownloadManager downloadManager;
	private ExpandableListView downloadListView, downloadHistoryListView;
	private DownloadJobAdapter downloadJobAdapter;
	private DownloadExpandAdapter downloadExpandAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.activity_download_management_layout);
		initUi();
		initListener();
	}

	private void initListener() {
		findViewById(R.id.go_back_btn).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void initUi() {
		mInflater = getLayoutInflater();
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		cursorWidth = dm.widthPixels / 2;
		shsView = (SyncHorizontalScrollView) findViewById(R.id.mhsv);
		rl_scroll = (RelativeLayout) findViewById(R.id.rl_scroll);
		tab_content = (RadioGroup) findViewById(R.id.tab_content);
		cursor = (ImageView) findViewById(R.id.cursor);
		LayoutParams cursor_Params = cursor.getLayoutParams();
		cursor_Params.width = cursorWidth;// 初始化滑动下标的宽
		cursor.setLayoutParams(cursor_Params);
		shsView.setSomeParam(rl_scroll, this);
		channels.add("正在下载");
		channels.add("下载历史");
		initTabContent();
		creatViewPager();
		initTabValue();
	}

	// 初始化Tabcontent
	private void initTabContent() {
		for (int i = 0; i < channels.size(); i++) {
			RadioButton radioButton = (RadioButton) mInflater.inflate(R.layout.tab_group_item, null);
			radioButton.setId(i);
			radioButton.setText(channels.get(i));
			radioButton.setLayoutParams(new LayoutParams(cursorWidth, LayoutParams.FILL_PARENT));
			rb_pages.add(radioButton);

		}
	}

	private void initTabValue() {
		tab_content.removeAllViews();
		for (int i = 0; i < listViews.size(); i++) {
			rb_pages.get(i).setText(channels.get(i));
			tab_content.addView(rb_pages.get(i));
		}
		tab_content.setOnCheckedChangeListener(tab_onCheckedChangeListener);
	}

	/**
	 * 初始化ViewPager
	 */
	private void creatViewPager() {
		if (listViews == null) {
			listViews = new ArrayList<View>();
			listViews.add(createDownloadingView());
			listViews.add(createDownloadHistoryView());
		}
		vPager = new MyViewPager(context, R.id.vPager, listViews).getAwesomePager();
		vPager.setOnPageChangeListener(new MyOnPageChangeListener());
		vPager.setCurrentItem(0);
		updataDownloadListView();
	}

	private View createDownloadingView() {
		View v = mInflater.inflate(R.layout.download_ing_layout, null);
		downloadListView = (ExpandableListView) v.findViewById(R.id.download_list);
		downloadListView.setGroupIndicator(null);
		downloadJobAdapter = new DownloadJobAdapter(context, new ArrayList<DownloadJob>());
		downloadListView.setAdapter(downloadJobAdapter);
		downloadManager = DownloadManager.getInstance(context);
		downloadManager.setDownloadJobAdapter(downloadJobAdapter);
		downloadManager.setMainHanlder(mHandler);
		return v;
	}

	private View createDownloadHistoryView() {
		View v = mInflater.inflate(R.layout.download_history_layout, null);
		downloadHistoryListView = (ExpandableListView) v.findViewById(R.id.app_download_history_list);
		downloadHistoryListView.setGroupIndicator(null);
		downloadExpandAdapter = new DownloadExpandAdapter(context, new ArrayList<DownloadEntity>());
		downloadHistoryListView.setAdapter(downloadExpandAdapter);
		return v;
	}

	private Handler mHandler = new Handler() {
		ProgressDialog dialog ;
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				updataDownloadListView();
				break;
			case 1:
				dialog = new ProgressDialog(context);
				dialog.setMessage("正在取消...");
				dialog.show();
			case 2 :
				dialog.dismiss();
			default:
				break;
			}
		}

	};

	public void updataDownloadListView() {
		if (!YimiApplication.jobList.isEmpty()) {
			downloadListView.setVisibility(View.VISIBLE);
			downloadJobAdapter.updateListData(YimiApplication.jobList);
		} else {
			downloadListView.setVisibility(View.GONE);
		}
		if (!YimiApplication.downloadHistoryList.isEmpty()) {
			downloadHistoryListView.setVisibility(View.VISIBLE);
			downloadExpandAdapter.updateListData(YimiApplication.downloadHistoryList);
		} else {
			downloadHistoryListView.setVisibility(View.GONE);
		}
	}

	// 页卡切换监听
	public class MyOnPageChangeListener implements OnPageChangeListener {
		@Override
		public void onPageSelected(int position) {
			if (rb_pages != null && rb_pages.size() > position) {
				((RadioButton) rb_pages.get(position)).performClick();
			}
			updataDownloadListView();
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	// RadioGroup点击CheckedChanged监听
	private OnCheckedChangeListener tab_onCheckedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			try {
				if (tab_content != null && tab_content.getChildCount() > 0 && tab_content.getChildAt(checkedId) != null) {
					TranslateAnimation _TranslateAnimation = new TranslateAnimation(mCurrentCheckedRadioLeft,
							((RadioButton) tab_content.getChildAt(checkedId)).getLeft(), 0f, 0f);
					// 匀速
					_TranslateAnimation.setInterpolator(new LinearInterpolator());
					_TranslateAnimation.setDuration(100);
					// 动画执行后，控件将停留在动画结束的状态
					_TranslateAnimation.setFillAfter(true);
					cursor.startAnimation(_TranslateAnimation);
					vPager.setCurrentItem(checkedId);// 让下方ViewPager跟随上面的HorizontalScrollView切换
					mCurrentCheckedRadioLeft = ((RadioButton) tab_content.getChildAt(checkedId)).getLeft();
					shsView.smoothScrollTo((checkedId > 1 ? ((RadioButton) tab_content.getChildAt(checkedId)).getLeft()
							: 0) - ((RadioButton) tab_content.getChildAt(2)).getLeft(), 0);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	};
}
